package com.hmall.trade.amqp;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.trade.contents.MQContents;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RequiredArgsConstructor
public class OrderDelayMessageListener {
    private final IOrderService orderService;
    private final PayClient payClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQContents.DELAY_ORDER_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(name = MQContents.DELAY_EXCHANGE_NAME, durable = "true", delayed = "true"),
            key = {MQContents.DELAY_ORDER_KRY}
    ))
    public void listenDelayPayStatusQuery(Long orderId) {

        //查询订单
        Order order = orderService.getById(orderId);
        //判断订单状态
        if (order == null || order.getStatus() != 1) {//已付款
            return;
        }
        //未付款,查询支付流水
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);

        //判断支付流水状态
        if (payOrderDTO == null) {
            log.error("查询支付流水失败,订单id为" + orderId);
            throw new RuntimeException("查询支付流水失败");
        }
        Integer status = payOrderDTO.getStatus();
        //如果已支付,则标记当前订单为已支付
        if (status == 3) { //付状态，0：待提交，1:待支付，2：支付超时或取消，3：支付成功
            orderService.markOrderPaySuccess(orderId);
        }
        // TODO 如果未支付就将当前订单的状态改为已取消,并将商品数量回滚
        else {
            orderService.cancelOrder(orderId);
        }


    }
}
